package com.khyr.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 宋一恒
 * @version 1.0
 */
@Configuration
public class RabbitConfig {
    // 普通队列和交换机
    private String exchangeName = "delayed.topic.exchange";
    private String queueName = "delayed.queue";

    // 死信队列和交换机
    private String deadExchangeName = "dead.letter.exchange";
    private String deadQueueName = "dead.letter.queue";

    // 创建普通队列（绑定死信交换机）
    @Bean
    public Queue delayedQueue() {
        return QueueBuilder.durable(queueName)
                .withArgument("x-dead-letter-exchange", deadExchangeName) // 绑定死信交换机
                .withArgument("x-dead-letter-routing-key", "dead.routing.key") // 死信路由键
                .withArgument("x-message-ttl", 60000)  // 1分钟（单位：毫秒）
                .build();
    }

    // 创建死信队列
    @Bean
    public Queue deadLetterQueue() {
        return QueueBuilder.durable(deadQueueName).build();
    }

    // 创建 Topic 类型的主交换机
    @Bean
    public TopicExchange delayedExchange() {
        return new TopicExchange(exchangeName);
    }

    // 创建死信交换机（建议使用 Fanout 类型）
    @Bean
    public FanoutExchange deadLetterExchange() {
        return new FanoutExchange(deadExchangeName);
    }

    // 绑定普通队列到主交换机（使用 Topic 路由规则）
    @Bean
    public Binding delayedBinding() {
        return BindingBuilder.bind(delayedQueue())
                .to(delayedExchange())
                .with("delayed.#"); // 匹配所有以 delayed 开头的路由键
    }

    // 绑定死信队列到死信交换机
    @Bean
    public Binding deadLetterBinding() {
        return BindingBuilder.bind(deadLetterQueue())
                .to(deadLetterExchange());
    }
}
